﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Chat;
using System.Windows.Browser;

namespace HomeOverlayUI
{
    public partial class MainPage : UserControl
    {
        protected Client _client = null;

        string username;

        double X;
        double Y;

        double XTollerance = 400;
        double YTollerance = 400;

        int navigationLevel = 0; //0=off, 1= tree/maillist/mail

        int nl1State = 0; // 0=nothing,  1=tree, 2=mail list 3= mail detail


        public MainPage(string un)
        {
            InitializeComponent();
            username = un;
            attemptSignin();

            gn1.Visibility = Visibility.Collapsed;
            resetNavigation1();

            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

        }




        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            if (navigationLevel == 1)
            {
                resetNavigation1();


                GeneralTransform gt = ctlMousePointer.RenderTransform;
                Point pt = gt.Transform(new Point(0,0));

                IEnumerable<UIElement> found = VisualTreeHelper.FindElementsInHostCoordinates(pt, gn1);

                if (found.Count() > 0)
                {
                    string ctlName = ((FrameworkElement)found.First()).Name;

                    var foundctl = gn1.FindName(ctlName);

                    if (foundctl != null && foundctl is Rectangle)
                    {
                        ((Rectangle)foundctl).Opacity = 0.5;

                        switch (ctlName.ToLower())
                        {
                            case "gn1tree": nl1State = 1; break;
                            case "gn1mail": nl1State = 2; break;
                            case "gn1maildetail": nl1State = 3; break;
                        }
                    }

                }
                else
                {
                    nl1State = 0;
                }
                lblFeedback.Text = nl1State.ToString();

            }
        }

        void resetNavigation1()
        {
            
            gn1Mail.Opacity = 0;
            gn1MailDetail.Opacity = 0;
            gn1Tree.Opacity = 0;
        }



        bool turnOffMessages = false;


        private void ProcessText(DateTime dt, string text)
        {
            if (turnOffMessages) return;

            this.Dispatcher.BeginInvoke(() =>
            {
                string[] parts = text.Split(",".ToCharArray());
                if (parts[0] == "mouse")
                {
                    X = double.Parse(parts[1]);
                    Y = double.Parse(parts[2]);

                    if (X <= 0) X = XTollerance - Math.Abs(X);
                    else X = XTollerance + X;


                    if (Y >= 0) Y = YTollerance - Y;
                    else Y = YTollerance + Math.Abs(Y);

                    //lblFeedback.Text = X.ToString() ;

                    X = this.ActualWidth * (X / 800);
                    Y = this.ActualHeight * (Y / 800);
                    
                    lblX.Text = X.ToString();
                    lblY.Text = Y.ToString();


                    ((DoubleAnimation)sbMoveMouse.Children[0]).To = X;
                    ((DoubleAnimation)sbMoveMouse.Children[1]).To = Y;
                    sbMoveMouse.Begin();

                } else if (parts[0] == "action")
                {
                    switch (parts[1])
                    {
                        case "push_tempcommentout":
                            #region Push Action
                            if (navigationLevel == 0)
                            {
                                gn1.Visibility = Visibility.Visible;
                                navigationLevel++;
                            }
                            else if (navigationLevel == 1)
                            {
                                if (nl1State == 0)
                                {
                                    navigationLevel = 0;
                                    gn1.Visibility = Visibility.Collapsed;
                                }
                                else
                                {
                                    HtmlDocument doc = HtmlPage.Document;
                                    HtmlElement divTree = doc.GetElementById("pnlTree");
                                    HtmlElement divMailList = doc.GetElementById("divGridPanel");
                                    HtmlElement divRightPane = doc.GetElementById("RightPane");
                                    HtmlElement divAccordion = doc.GetElementById("Accordion");
                                    //HtmlElement divMailDetail = (HtmlElement)divRightPane.Children[2];
                                    

                                    divTree.SetStyleAttribute("background", "");
                                    divMailList.SetStyleAttribute("background", "");
                                    //divMailDetail.SetStyleAttribute("background", "");


                                    switch (nl1State)
                                    {
                                        case 1:  //tree
                                            //divTree.SetStyleAttribute("background", "green");
                                            lblFeedback.Text = "cheatNavigate";
                                            try
                                            {
                                                //HtmlWindow win =  HtmlPage.PopupWindow(new Uri("http://keystoneviewer/Member/SLViewer.aspx?filterId=28541"), "blank", new HtmlPopupWindowOptions() { Width = 800, Height = 600 });


                                                HtmlPage.Window.Navigate(new Uri("http://keystonejf/Member/SLViewer.aspx?filterId=28541", UriKind.Absolute), "blank");

                                                turnOffMessages = true;
                                                //HtmlPage.Window.Invoke("LaunchViewer");
                                            }
                                            catch (Exception ex){
                                                lblFeedback.Text = ex.Message;
                                            }
                                            break;
                                        case 2: //mail list
                                            //divMailList.SetStyleAttribute("background", "green");
                                            break;
                                        case 3: //mail detail
                                            //divMailDetail.SetStyleAttribute("background", "green");
                                            break;
                                    }
                                }
                            }
                            #endregion
                            break;


                    }
                    lblFeedback.Text = parts[1];
                }
                else
                {
                    //lblFeedback.Text = parts[1];
                }


                //output.Text += time.ToString("h:mm:ss") + "\t" + text + Environment.NewLine;
                

                //autoScroll();
            });
        }

        private void initAndSignInToChat()
        {
            int serverPort = 4520;

            _client = new Client("localhost", serverPort, "HomeOverlay");

            _client.SignedIn += new EventHandler<EventArgs>(_client_SignedIn);
            _client.SignedOut += new EventHandler<EventArgs>(_client_SignedOut);
            _client.SignInFailed += new EventHandler<ClientEventArgs>(_client_SignInFailed);
            _client.ChatReceived += new EventHandler<MessageEventArgs>(_client_ChatReceived);
            _client.UserJoined += new EventHandler<MessageEventArgs>(_client_UserJoined);
            _client.UserLeft += new EventHandler<MessageEventArgs>(_client_UserLeft);
            _client.UserList += new EventHandler<MessageEventArgs>(_client_UserList);
            _client.SystemEvent += new EventHandler<ClientEventArgs>(_client_SystemEvent);
            _client.SignIn();
        }

        void _client_SignInFailed(object sender, ClientEventArgs e)
        {
            ProcessText(e.Time, "SignIn Failed: " + e.Text);
            this.Dispatcher.BeginInvoke(() =>
            {
                
            });
        }

        void _client_UserList(object sender, MessageEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {

            });
        }



        void _client_SystemEvent(object sender, ClientEventArgs e)
        {
            ProcessText(e.Time, "System Event: " + e.Text);
        }

        void _client_UserJoined(object sender, MessageEventArgs e)
        {
            string newUser = e.Message.Data[0];

            ProcessText(e.Message.Time, "User '" + newUser + "' joined.");

            this.Dispatcher.BeginInvoke(() =>
            {

            });
        }

        void _client_UserLeft(object sender, MessageEventArgs e)
        {
            string newUser = e.Message.Data[0];

            ProcessText(e.Message.Time, "User '" + newUser + "' left.");

            this.Dispatcher.BeginInvoke(() =>
            {
 
            });
        }

        void _client_ChatReceived(object sender, MessageEventArgs e)
        {
            if (turnOffMessages) return;

            //ProcessText(e.Message.Time, e.Message.Data[0] + ": " + e.Message.Data[1]);
            ProcessText(e.Message.Time, e.Message.Data[1]);
        }

        void _client_SignedIn(object sender, EventArgs e)
        {
            ProcessText(DateTime.Now, "SignedIn");
            this.Dispatcher.BeginInvoke(() =>
            {
                
            });
        }

        void _client_SignedOut(object sender, EventArgs e)
        {
            ProcessText(DateTime.Now, "Signed Out ");
            this.Dispatcher.BeginInvoke(() =>
            {
                
            });
        }

        void _client_ClientEvent(object sender, ClientEventArgs e)
        {
            if (turnOffMessages) return;

            ProcessText(e.Time, e.Text);
        }



        private void attemptSignin()
        {
            bool valid = true;
            string errorMessage = string.Empty;

            

            if (valid)
            {
                
                initAndSignInToChat();
            }
            else
            {
                System.Windows.MessageBox.Show(errorMessage);
            }
        }

    }
}
